﻿var chartURL = "";
var dialog;

function pollChartChange() {
    var intervalID = setInterval(function () {
        var url = document.getElementById("excelUrl");
        if (url && url.value != chartURL && url.value.length > 0) {
            chartURL = url.value;

            var jsonUrl = window.location.protocol + "//" + window.location.host + "/_vti_bin/ExcelRest.aspx" + chartURL + "/Model/Charts?$format=json";
            var executor = new SP.RequestExecutor(_spPageContextInfo.siteAbsoluteUrl);

            dialog = SP.UI.ModalDialog.showWaitScreenWithNoClose(SP.Res.dialogLoading15, 'Fetching images from Excel file...');

            executor.executeAsync(
                {
                    url: jsonUrl,
                    method: "GET",
                    headers: { "Accept": "application/json; odata=verbose" },
                    success: onGetChartsSuccess,
                    error: onGetChartsFail
                }
            );
        }
        clearFields(false);

    }, 250); // 250 ms check
}

function clearFields(clearAll) {
    var url = document.getElementById("excelUrl");
    if ((url && url.value.length == 0) || clearAll) {
        var chartName = document.getElementById("chartName");
        chartName.value = "";
        var dropdown = document.getElementById("chartPicker");
        dropdown.options.length = 0;
    }
}


function onGetChartsSuccess(data) {
    try {
        var jsonObject = JSON.parse(data.body);
        //var results = jsonObject.d.query.PrimaryQueryResult.RelevantResults.Table.Rows.results;
        if (jsonObject.items && jsonObject.items.length > 0) {
            var dropdown = document.getElementById("chartPicker");
            dropdown.options.length = 0;

            for (var i = 0; i < jsonObject.items.length; i++) {
                var item = jsonObject.items[i];
                var opt = document.createElement("option");
                opt.text = item.name;
                opt.value = item.name;
                dropdown.options.add(opt);
            }
        }
        else {
            alert("Could not find any charts.");
        }
    } catch (e) {
        alert("Failed to retrieve charts.");
    }
    dialog.close();
}

function onGetChartsFail(data, errorCode, errorMessage) {
    dialog.close();
    clearFields(true);
}

function kickIt() {
    SP.SOD.executeFunc('sp.requestexecutor.js', 'SP.RequestExecutor', pollChartChange);
}

_spBodyOnLoadFunctionNames.push("kickIt");